/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/alerts.js
*/
//----------------------------------------------------------------------------------------------------
//  Constructor and Class Methods
//----------------------------------------------------------------------------------------------------

function AlertsHub ()
{
    var s, b;
    this.getSerializer = function ()
    {
        if(!s) { s = new Serializer(); }
        return s;
    }

    this.getContentBuffer = function ()
    {
        if(!b) { b = new ContentBuffer(); }
        return b;
    }

    this.init();
}

//----------------------------------------------------------------------------------------------------
//  Constants and Defaults
//----------------------------------------------------------------------------------------------------

AlertsHub.prototype.API_URL = '/ft/markets/data/AlertAPI.asp';
AlertsHub.prototype.messageFormat = { 'HTML': 'htmlMessage', 'Text': 'textMessage' };
AlertsHub.prototype.PREVIEW_HEIGHT = 700;
AlertsHub.prototype.PREVIEW_WIDTH = 725;

//----------------------------------------------------------------------------------------------------
//  Public Instance Methods
//----------------------------------------------------------------------------------------------------

AlertsHub.prototype.init = function ()
{
    this.initPreferencesForm();
    this.initEquitySearchForm();
    this.initExampleAlerts();
}

AlertsHub.prototype.initPreferencesForm = function ()
{
    this.preferencesForm = WSDOM.Element.get('alertPreferences');

    this.drawVacationStopSelect();

    Events.add({
        element: WSDOM.Element.get('preferencesSubmit'),
        type: 'click',
        handler: this.updatePreferences,
        context: this
    });
}

AlertsHub.prototype.initEquitySearchForm = function ()
{
    var input = WSDOM.Element.get('equitySearchInput'),
        submit = WSDOM.Element.get('equitySearchSubmit');

    var s = new SymbolSearch();
    s.CSS_RESULTS = 'symbolSearch';
    s.FORM_INPUT_SELECTOR = "input[name='equitySearchInput']";
    s.setForm(WSDOM.Element.get('equitySearchForm'));
    s.setRequestor( this.getContentBuffer() );
    s.go = function (symbol) {
        this.clearResults();
        this.query = symbol;
        this.elInput.value = symbol;
    };

    Events.add({
        element: input,
        type: 'focus',
        handler: function () { input.value = '' },
        context: this
    });

    Events.add({
        element: submit,
        type: 'click',
        handler: this.drawEquityAlertForm,
        context: this,
        data: {
            inputField: input
        }
    });
}

AlertsHub.prototype.initExampleAlerts = function ()
{
    var textAlert = new Image(); textAlert.src = '/ft/resources/image/AlertText.png';
    var htmlAlert = new Image(); htmlAlert.src = '/ft/resources/image/AlertHTML.png';

    var exampleAlerts = {
        'text': textAlert,
        'html': htmlAlert
    };

	var ah = this;
    function displayExample (e, element, data)
    {
        if(this.showShotWin) {
          this.showShotWin.close();
        }
        var example = exampleAlerts[data.type];
        this.showShotWin = window.open('showShot.asp?img=' + example.src, 'alertExample', 'width=' + ah.PREVIEW_WIDTH + ',height=' + ah.PREVIEW_HEIGHT + ',status=no,toolbar=no,resizable=yes,location=no,menubar=no,scrollbars=yes');
    }

    Events.add({
        element: WSDOM.Element.get('wsod-text-alert-example'),
        type: 'click',
        handler: displayExample,
        data: {
            type: 'text'
        }
    });

    Events.add({
        element: WSDOM.Element.get('wsod-html-alert-example'),
        type: 'click',
        handler: displayExample,
        data: {
            type: 'html'
        }
    });
}

AlertsHub.prototype.drawVacationStopSelect = function (start, end)
{
    var vacationStart   = start || new Date();
    var vacationEnd     = end   || new Date();

	this.vacationHold = new DateSelect({
		container:  WSDOM.Element.get('fromDateSelect'),
		yearCount:  5,
		date:       [vacationStart, vacationEnd],
		labels:     ['Start holding my alerts', 'Resume sending my alerts'],
        monthType:  'abbr'
	});
	
  //Add drop down event handlers
  var monthSelects = this.vacationHold.monthSelect;
  var daySelects = this.vacationHold.daySelect;
  var yearSelects = this.vacationHold.yearSelect;
  
  Events.add({
      element: monthSelects,
      type: "change",
      handler: this.toggleVacationCheck,
      context: this
  });

  Events.add({
      element: daySelects,
      type: "change",
      handler: this.toggleVacationCheck,
      context: this
  });

  Events.add({
      element: yearSelects,
      type: "change",
      handler: this.toggleVacationCheck,
      context: this
  });
}

AlertsHub.prototype.getCustomerPreferences = function ()
{
    var buffer = this.getContentBuffer();
    buffer.load({
        url: this.API_URL,
        method: 'post',
        data: {
            method: 'getProfile'
        },
        onload: this.populatePreferencesForm,
		contentType: "text/javascript",
        context: this,
        preventEval: true
    });
}

AlertsHub.prototype.populatePreferencesForm = function (cb)
{
    this.profile = this.getSerializer().deserialize(cb.getResult());

    WSDOM.Element.get('emailAddress').value = this.profile.Address;
    WSDOM.Element.get('emailAddress').defaultValue = this.profile.Address;
    WSDOM.Element.get( this.messageFormat[ this.profile.Format ] ).checked = true;
    WSDOM.Element.get('vacationStop').checked = this.profile.VacationApplies;

    if( this.profile.VacationApplies )
    {
        WSDOM.Element.removeChildNodes(WSDOM.Element.get('fromDateSelect'));
        this.drawVacationStopSelect(this.profile.VacationStart, this.profile.VacationEnd);
    }

    WSDOM.Element.get('hasProfile').value = this.profile.hasProfile;

    this.drawPortfolioAlertsTable();
    this.drawEquityAlertsTable();
}

AlertsHub.prototype.toggleVacationCheck = function ()
{
    WSDOM.Element.get("vacationStop").checked = true;
}

AlertsHub.prototype.updateAlertsTable = function (cb)
{
    this.profile = this.getSerializer().deserialize(cb.getResult());
    this.drawEquityAlertsTable();
    this.drawPortfolioAlertsTable();
}

AlertsHub.prototype.drawPortfolioAlertsTable = function ()
{
    var table = new PortfolioAlertsTable({
        alerts: this.profile.portfolioAlerts,
        parentElement: WSDOM.Element.get('portfolioAlertsTable'),
        manager: this,
        details: WSDOM.Element.get('portfolioAlertsDetails')
    });

    table.draw();

    return;
}

AlertsHub.prototype.drawEquityAlertsTable = function ()
{
    var table = new EquityAlertsTable({
        alerts: this.profile.customerAlerts,
        parentElement: WSDOM.Element.get('equityAlertsTable'),
        manager: this,
        details: WSDOM.Element.get('equityAlertsDetails')
    });

    table.draw();

    return;
}

AlertsHub.prototype.updatePreferences = function (e, element)
{
    Events.cancel(e);
    
    //Some quick validation - Some of this should be refactored into something more elegant
    var bGoodData = true;
    var errMsg = "";
    
    if(this.preferencesForm.emailAddress.value.length < 2) {
      bGoodData = false;
      errMsg = "Please specify an email address.";
    } else { //OK run further checks for validity
      if(/\@/.test(this.preferencesForm.emailAddress.value)) {
        var aryEmailParts = this.preferencesForm.emailAddress.value.split("@");

        if(aryEmailParts[0].length < 2) { //test first part of email
          bGoodData = false;
          errMsg = "Please specify a valid email address.";
        } 
        
        if((bGoodData && /\./.test(aryEmailParts[1]))) {
          //one last further check to see if the TLD is correct
          var aryEmailTLDParts = aryEmailParts[1].split(".");
          for(var i in aryEmailTLDParts) { //Look at each segment of post-dot
            if(aryEmailTLDParts[i].length < 2 && "function" != typeof aryEmailTLDParts[i]) { 
              bGoodData = false;
              break;
            }
          }
          if(!bGoodData) {
            errMsg = "Please specify a valid email address.";
          }
        } else if(bGoodData) { //no dots in TLD part
          bGoodData = false;
          errMsg = "Please specify a valid email address.";
        }
        
      } else { //no @ in email
        bGoodData = false;
        errMsg = "Your email address needs an @ in it.";
      }
    }
    
    if(bGoodData && this.preferencesForm.vacationStop.checked) { //Now Check the date
      //Set start for midnight and end for one sec before midnight the next day
      this.vacationHold.selectDate[0].setHours(0, 0, 0);
      this.vacationHold.selectDate[1].setHours(0, 0, 0);
      var currDate = new Date();
      currDate.setHours(0, 0, 0);
      var stDate = (new Date(this.vacationHold.selectDate[0])).getTime();
      var edDate = (new Date(this.vacationHold.selectDate[1])).getTime();
      
      if(stDate >= edDate) {
        bGoodData = false;
        errMsg = "Start date must fall before the end date.";
      } else if(edDate <= currDate.getTime()) {
        bGoodData = false;
        errMsg = "End date must fall after the current date.";
      }
    }

    var s = new FormSerializerLite(),
        contents = s.serialize( this.preferencesForm ),
        vacation = this.getSerializer().serialize( this.vacationHold.getDatesAlerts() );

    var buffer = this.getContentBuffer();
    if(bGoodData) {
      buffer.load({
          url: this.API_URL,
          method: 'post',
          data: {
              method: 'updatePreferences',
              preferences: contents,
              vacation: vacation
          },
          onload: this.confirmChange,
          context: this,
		  contentType: "text/javascript",
          preventEval: true
      });
    } else {
       this.getErrorPopup().draw(errMsg);
    }
}


AlertsHub.prototype.confirmChange = function (cb)
{
    var change = this.getSerializer().deserialize(cb.getResult());

    if( change == 1 )
    {
      //Some of this should be refactored into something more elegant
      if(this.preferencesForm.emailAddress.defaultValue != this.preferencesForm.emailAddress.value) {
        this.getErrorPopup().draw("Your email address has been changed.");
        this.preferencesForm.emailAddress.defaultValue = this.preferencesForm.emailAddress.value;
      } else {
        this.getErrorPopup().draw('Profile updated successfully');
      }
    }
    else
    {
        this.getErrorPopup().draw('There was a problem updating your profile');
    }
}

AlertsHub.prototype.drawEquityAlertForm = function (e, element, data)
{
    Events.cancel(e);

    var symbol = WSDOM.Element.get('equitySearchInput').value;

    var alertsPopup = new AlertsForm({
        symbol: WSDOM.Element.get('equitySearchInput').value,
        parentElement: WSDOM.Element.get('wsod'),
        hub: this
    });
    alertsPopup.draw();
}

AlertsHub.prototype.drawEditForm = function (e, element, data)
{
    if( data.type == 'portfolio' )
    {
        this.drawPortfolioEditForm(data);
    }
    else if( data.type == 'equity' )
    {
        this.drawEquityEditForm(data);
    }
}

AlertsHub.prototype.drawEquityEditForm = function (myAlert)
{
    var editForm = new AlertsForm({
        symbol: myAlert.FTSymbol,
        parentElement: WSDOM.Element.get('wsod'),
        hub: this
    });
    editForm.draw(myAlert);
}

AlertsHub.prototype.drawPortfolioEditForm = function (myAlert)
{
    var editForm = new PortfolioAlertsForm({
        symbol: myAlert.FTSymbol,
        parentElement: WSDOM.Element.get('wsod'),
        hub: this
    });
    editForm.draw(myAlert);
}

AlertsHub.prototype.deleteAlert = function (e, element, data)
{
    var goAhead = confirm( 'Are you sure you want to delete this alert?' );
    if(!goAhead)
    {
        return;
    }
    
    var myAlert = this.getSerializer().serialize(data);

    var buffer = this.getContentBuffer();
    buffer.load({
        url: this.API_URL,
        method: 'post',
        data: {
            method: 'deleteAlert',
            input: myAlert
        },
        onload: this.populatePreferencesForm,
        context: this,
		contentType: "text/javascript",
        preventEval: true
    });
}
AlertsHub.prototype.getErrorPopup = function() 
{
	var ep = new ErrorPopup();
	this.getErrorPopup = function() 
	{
		return ep;
	}
	return this.getErrorPopup();
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------

function AlertsTable (oArgs)
{
    for( var field in oArgs )
    {
        this[field] = oArgs[field];
    }
}

AlertsTable.prototype.headerFields = { 
    'Equity':           25,
    '&nbsp;':           4,
    'Alert Type Set':   63, 
    'Actions':          8 
};

AlertsTable.prototype.draw = function ()
{
    this.table = WSDOM.Element.create('table', { className: 'equityAlerts' }, null);
    WSDOM.Element.removeChildNodes(this.parentElement);

    if(!this.getAlertsCount())
    {
        this.hideDetails('show');
        return; 
    }

    this.drawTableHead();
    this.drawTableBody();

    this.parentElement.appendChild(this.table);

    this.drawLegend();

    var showDetails = ( this.getAlertsCount() ) ? 'hide' : 'show';
    this.drawDetailsLink();
    this.hideDetails(showDetails);
}

AlertsTable.prototype.drawTableHead = function ()
{
    this.colGroup = WSDOM.Element.create('colgroup', {}, null, this.table);

    this.head = WSDOM.Element.create('thead', {}, null, this.table);
    var trow = WSDOM.Element.create('tr', {}, null, this.head)

    for( var header in this.headerFields )
    {
        WSDOM.Element.create('col', { width: this.headerFields[header] + '%' }, null, this.colGroup);
        WSDOM.Element.create('th', {}, header, trow);
    }
}

AlertsTable.prototype.drawTableBody = function ()
{
    this.body = WSDOM.Element.create('tbody', {}, null, this.table);

    var symbol, company, i, myAlert, actions;

    for( var symbol in this.alerts )
    {
        company = this.alerts[symbol];

        for( var i = 0; i < company.alerts.length; i++ )
        {
            myAlert = company.alerts[i];
            myAlert.FTSymbol = company.FTSymbol;

            row = WSDOM.Element.create('tr', {}, null, this.body);
            rowSpan = company.alerts.length;

            if( i == 0 )
            {
                var companyCell = this.drawLabelCell(company, rowSpan);
                row.appendChild(companyCell);
            }

            var hasFired = WSDOM.Element.create('td', {}, null, row);
            if( myAlert.hasFired )
            {
                WSDOM.Element.create('span', { className: 'icon action icon-alert-sent' }, '&nbsp;', hasFired );
                this.hasFiredAlerts = true;
            }
            WSDOM.Element.create('td', {}, myAlert.description, row);

            var actionCell = this.drawActionsCell(myAlert);
            row.appendChild(actionCell);
        }
    }
}

AlertsTable.prototype.drawLabelCell = function (company, rowspan)
{
    throw new Error('This method must be overridden');
}

AlertsTable.prototype.drawActionsCell = function (myAlert)
{
    var cell = WSDOM.Element.create('td', { className: 'actionCell' }, null);

    cell.appendChild( this.drawEditIcon( myAlert ) );
    cell.appendChild( this.drawDeleteIcon( myAlert ) );

    return cell;
}

AlertsTable.prototype.drawEditIcon = function (myAlert)
{
    var icon = WSDOM.Element.create('a', 
            { href: 'javascript:void(0)', className: 'icon action icon-edit' }, 
            '&nbsp;');

    Events.add({
        element: icon,
        type: 'click',
        handler: this.manager.drawEditForm,
        data: myAlert,
        context: this.manager
    });

    return icon;
}

AlertsTable.prototype.drawDeleteIcon = function (myAlert, action)
{
    var icon = WSDOM.Element.create('a', 
            { href: 'javascript:void(0)', className: 'icon action icon-delete-close' }, 
            '&nbsp;');

    Events.add({
        element: icon,
        type: 'click',
        handler: this.manager.deleteAlert,
        data: myAlert,
        context: this.manager
    });

    return icon;
}

AlertsTable.prototype.drawDetailsLink = function ()
{
    var linkDiv = WSDOM.Element.create('div', { className: 'submitButtonSection' }, null, this.parentElement);
    this.detailsLink = WSDOM.Element.create('a', { href: 'javascript:void(0)', className: 'exampleLink' }, '- Hide Details', linkDiv);
    
    //  Disclaimer Text
    var disclaimer = WSDOM.Element.create('span', { className: 'alertDisclaimer' }, null, linkDiv);
    WSDOM.Element.create('b', {}, 'Note: ', disclaimer);
    var text = document.createTextNode('Alerts will be delivered within the hour of the requested time');
    disclaimer.appendChild(text);

    this.hideEvent = Events.add({
        element: this.detailsLink,
        type: 'click',
        handler: this.toggleDetails,
        context: this
    });
}

AlertsTable.prototype.hideDetails = function (state)
{
    if( state == 'show' )
    {
        this.details.style.display = 'block';
        this.setDetailsLink('- Hide Details');
    }
    else if( state == 'hide' )
    {
        this.details.style.display = 'none';
        this.setDetailsLink('+ View Details');
    }
}

AlertsTable.prototype.toggleDetails = function ()
{
    if( this.details.style.display == 'none' )
    {
        this.hideDetails('show');
    }
    else
    {
        this.hideDetails('hide');
    }
}

AlertsTable.prototype.setDetailsLink = function (value)
{
    if( !this.detailsLink )
    {
        return;
    }

    WSDOM.Element.removeChildNodes(this.detailsLink);
    this.detailsLink.appendChild( document.createTextNode(value) );
}

AlertsTable.prototype.getAlertsCount = function ()
{
    var count = 0;
    for( var field in this.alerts )
    {
        count++;
    }

    return count;
}

AlertsTable.prototype.drawLegend = function ()
{
    if( !this.hasFiredAlerts ) { return; }

    var colspan = 0;
    for( var field in this.headerFields )
    {
        colspan++;
    }

    var foot    = WSDOM.Element.create('tfoot', {}, null, this.table);
    var row     = WSDOM.Element.create('tr', {}, null, foot);
    var cell    = WSDOM.Element.create('td', { 'colSpan': colspan }, null, row);

    WSDOM.Element.create('span', { className: 'icon action icon-alert-sent' }, '&nbsp;', cell );

    
    return cell;
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------

function EquityAlertsTable (oArgs)
{
    EquityAlertsTable.Super(this, null, [oArgs]);
}
EquityAlertsTable.Extend(AlertsTable);

EquityAlertsTable.prototype.drawLabelCell = function (company, rowspan)
{
    var cell = WSDOM.Element.create('td', { className: 'symbol', 'rowSpan': rowspan }, null);
    WSDOM.Element.create('a', { href: '/ft/tearsheets/performance.asp?s=' + escape(company.FTSymbol) }, company.DisplaySymbol, cell);
    WSDOM.Element.create('span', {}, ':' + company.ExchangeCode, cell);
    WSDOM.Element.create('span', { className: 'companyName' }, company.Name, cell);

    return cell;
}

EquityAlertsTable.prototype.drawLegend = function ()
{
    var cell = EquityAlertsTable.Super(this, 'drawLegend');
    WSDOM.Element.create('span', {}, 'Equity alert sent today', cell );
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------

function PortfolioAlertsTable (oArgs)
{
    PortfolioAlertsTable.Super(this, null, [oArgs]);
    this.sortAlerts();
    console.log(this);
}
PortfolioAlertsTable.Extend(AlertsTable);

PortfolioAlertsTable.prototype.headerFields = { 
    'Portfolio':        25,
    '&nbsp;':            4,
    'Alert Type Set':   63, 
    'Actions':           8 
};

PortfolioAlertsTable.prototype.sortAlerts = function ()
{
    var pf;

    function byTime (a, b)
    { 
        //var a = a.description, b = b.description;
        var a = a.SortOrder, b = b.SortOrder;
        if( a > b )
        {
            return 1;
        }
        else if (a < b )
        {
            return -1;
        }

        return 0;
    }

    for( var id in this.alerts )
    {
        this.alerts[id].alerts.sort(byTime);
    }
}

PortfolioAlertsTable.prototype.drawLabelCell = function (portfolio, rowspan)
{
    var cell = WSDOM.Element.create('td', { className: 'symbol', 'rowSpan': rowspan });
    WSDOM.Element.create('a', { href: '/ft/portfolio/performance.asp?containerName=' + new Serializer().serialize(portfolio.name) }, portfolio.name, cell);

    return cell;
}

PortfolioAlertsTable.prototype.drawLegend = function ()
{
    var cell = PortfolioAlertsTable.Super(this, 'drawLegend');
    WSDOM.Element.create('span', {}, 'Portfolio alert sent today', cell );
}

//----------------------------------------------------------------------------------------------------
// Error Popup
//----------------------------------------------------------------------------------------------------

function ErrorPopup() 
{
	ErrorPopup.Super(this);
	
	this.hasTitle(false);
	this.hasCloseLink(false);
}
ErrorPopup.Extend(Popup);

ErrorPopup.prototype.CSS_CLASS = "errorPopup";

ErrorPopup.prototype.getFrame = function() 
{
	var frame = ErrorPopup.Super(this, "getFrame");
	WSDOM.Element.addClass(frame, this.CSS_CLASS);
	
	var ok;
	WSDOM.Element.create("div", { "class": "popupFooter" }, [
		ok = WSDOM.Element.create("div", { "class": "basicButton"}, [
			WSDOM.Element.create("div", null, "OK")
		])
	], this.getCanvas());
	
	this.getCloseEvent().addElement(ok);
	
	this.getFrame = function() 
	{
		return frame;
	}
	
	return this.getFrame();
}

ErrorPopup.prototype.draw = function(errorMessage) 
{
	this.clearContent();
	WSDOM.Element.create("p", null, errorMessage, this.getContent());
	
	ErrorPopup.Super(this, "draw");
}

ErrorPopup.prototype.onClose = function() {
	var e = Events.add("errorPopupClose");
	this.onClose = function() {
		return e;
	}
	return this.onClose();
}

ErrorPopup.prototype.close = function(e) 
{
	ErrorPopup.Super(this, "close", arguments);
	this.onClose().fire(e);
}

/*
FILE CONCAT ADD FILE
PATH: /ft/resources/client/alertsPopup.js
*/
//----------------------------------------------------------------------------------------------------
//  Constructor and Class Methods
//----------------------------------------------------------------------------------------------------

function AlertsForm (oArgs)
{
    AlertsForm.Super(this);
	
	for( var field in oArgs )
    {
        this[field] = oArgs[field];
    }

    this.init();
}

AlertsForm.Extend(Popup);

//----------------------------------------------------------------------------------------------------
//  Constants and Defaults
//----------------------------------------------------------------------------------------------------

AlertsForm.prototype.QUOTE_API = '/ft/apis/quotes/Quote.asp';
//AlertsForm.prototype.ALERT_API = '/ft/apis/alerts/AlertAPI.asp';
AlertsForm.prototype.ALERT_API = '/ft/markets/data/AlertAPI.asp';

//----------------------------------------------------------------------------------------------------
//  Common Component Drawing Methods
//----------------------------------------------------------------------------------------------------
AlertsForm.prototype.init = function ()
{
    //this.parentElement = this.parentElement || document.body;
    this.buffer = new ContentBuffer();

    this.serializer = new Serializer();
    this.serializer.addNameExclusion('manager');

    this.formComponents = new Array();

    this.alertForms = {
        'priceDropsBelow':  PriceDropsBelowAlert,
        'priceRisesAbove':  PriceRisesAboveAlert,
        'periodHighLow':    PeriodHighLowAlert, // }          {  The PeriodHighLowAlert Form
        'periodLow':        PeriodHighLowAlert, // }----------{  is shared by both the PeriodHighAlert
        'periodHigh':       PeriodHighLowAlert, // }          {  and PeriodLowAlert objects
        'priceChange':      PriceChangeAlert,
        'priceAverage':     PriceAverageAlert,
        'volumeAverage':    VolumeAverageAlert,
        'priceVSIndex':     PriceVSIndexAlert
    };

    this.timezone = WSODTIMEZONE || 'GMT';
    this.timezoneOffset = WSODTIMEZONEOFFSET || '0';
}

AlertsForm.prototype.drawEditLink = function () {
    if( this.hub ){ return };
	if (this.editLink) { return };
	
    this.editLink = WSDOM.Element.create('a', { href: '/ft/markets/alerts/index.asp', className: 'editLink' },
            'Edit alert preferences', this.getHeader());
};

AlertsForm.prototype.drawSubmitButton = function () {
    var fieldset = WSDOM.Element.create('fieldset', { className: 'submitSet' }, null, this.form);

    var outerButton = WSDOM.Element.create('div', { className: 'basicButton' }, null, fieldset);
    var button = WSDOM.Element.create('div', {}, 'Save Alerts', outerButton);

    Events.add({
        element: button,
        type: 'click',
        handler: this.submitForm,
        context: this
    });
}

AlertsForm.prototype.draw = function (myAlert)
{
    this.buffer.load({
        url: this.ALERT_API,
        method: 'post',
        data: {
            method: 'getCompanyInfo',
            symbol: this.symbol
        },
        onload: this.validateCompanyInfo,
        context: this,
        preventEval: true,
        alertInstance: myAlert
    });
}

AlertsForm.prototype.validateCompanyInfo = function (cb)
{
    this.companyInfo = this.serializer.deserialize(cb.getResult());
    var myAlert = cb.contentPackage.alertInstance;

    if( this.companyInfo.status )
    {
        this.drawAlertForm(myAlert);
    }
    else
    {
        this.drawErrorMessage('The symbol you entered appears to be invalid.  Please enter a new symbol and try again.');
    }
}

AlertsForm.prototype.drawErrorMessage = function (message)
{
    var e = new ErrorPopup();
    e.draw('Invalid Symbol', message);
}

AlertsForm.prototype.drawAlertForm = function (myAlert)
{
	//  Draw Header Text and Links
	this.setTitleText('Equity Alerts For ' + this.companyInfo.DisplaySymbol);
    this.drawEditLink();
	
	this.clearContent();
    //  Draw Form
    this.form = WSDOM.Element.create('form', { id: 'alertForm', className: 'alertForm' }, null, this.getContent());

    //  Draw Per-alert Form Components
    if( myAlert )
    {
        var form = new this.alertForms[myAlert.name]({ manager: this });
        form.setAlertItem(myAlert);
        form.hideCheckBox(true);
        form.draw();
    }
    else
    {
        for( var field in this.alertForms )
        {
            //  workaround for form shared between alert types
            if( field == 'periodHigh' || field == 'periodLow' ){ continue; }

            var form = new this.alertForms[field]({ manager: this });
            form.draw();
        }
    }

    //  Draw Submit Button
    this.drawSubmitButton(this.form);
	
    //  Display quote and company info on alerts form
    for( var i = 0; i < this.formComponents.length; i++ )
    {
        this.formComponents[i].populateCompanyInfo();
    }

	AlertsForm.Super(this, "draw");
}

AlertsForm.prototype.submitForm = function (e, element)
{
    Events.cancel(e);

    var formContents = new Object(),
        currentForm, component,
        hasError = false;

    for( var i = 0; i < this.formComponents.length; i++ )
    {
        component = this.formComponents[i];
        if( component.toggle && component.toggle.checked )
        {
            currentForm = component.serialize();
            if( !currentForm )
            {
                hasError = true;
                continue;
            }
            else
            {
                formContents[ currentForm.name ] = currentForm;
            }
        }
    }

    if( hasError ){ return; }

    formContents = this.serializer.serialize(formContents);

    this.buffer.load({
        url: this.ALERT_API,
        method: 'post',
        data: {
            method: 'configureAlerts',
            alertsConfig: formContents 
        },
        onload: this.confirmSubmit,
        context: this,
        preventEval: true
    });
}

AlertsForm.prototype.confirmSubmit = function (cb)
{
    var response = this.serializer.deserialize(cb.getResult());

    if( response && !this.hub )
    {
        new ErrorPopup().draw('Success', 'Your alert was created successfully.');
    }

    this.updateCustomerAlerts(cb);
}

AlertsForm.prototype.updateCustomerAlerts = function (cb)
{
    this.getCloseEvent().fire();
    if( 'hub' in this )
    {
        this.hub.populatePreferencesForm(cb);
    }
}

//----------------------------------------------------------------------------------------------------
//  PortfolioAlertsForm
//
//  This form inherits from AlertsForm
//----------------------------------------------------------------------------------------------------

function PortfolioAlertsForm (oArgs)
{
    PortfolioAlertsForm.Super(this, null, [oArgs]);
}
PortfolioAlertsForm.Extend(AlertsForm);

PortfolioAlertsForm.prototype.init = function ()
{
    this.buffer = new ContentBuffer();

    this.formComponents = new Array();

    this.serializer = new Serializer();
    this.serializer.addNameExclusion('manager');

    if( !this.hub )
    {
        this.summary = this.serializer.deserialize(serializedCurrentPortfolioSummary);
        this.summary.ContainerID = this.summary.containerId; // Workaround for case mismatch between Portfolio and Alerts
    }
}


PortfolioAlertsForm.prototype.draw = function (myAlert)
{
	if (this.isVisible()) { return };

    if(!this.summary){ this.summary = myAlert; }
    if(!this.summary.ContainerName)
    {
        this.summary.ContainerName = this.summary.containerName;
    }
	
    //  Draw Header Text and Links
    this.setTitleText('Portfolio Alert For ' + this.summary.ContainerName);
    this.drawEditLink();
    WSDOM.Element.addClass(this.getFrame(), 'portfolioAlertFrame');

	this.clearContent();
	
    //  Draw Form
    this.form = WSDOM.Element.create('form', { id: 'alertForm', className: 'alertForm' }, null, this.getContent());

    var form = new PortfolioAlert({ manager: this });
    form.setAlertItem(myAlert);
    form.draw();

    this.drawSubmitButton(this.form);

	// this feels bad. I want to call my super super classes method, and skip my super classes method. I could always just overwrite that biatch.
    this.getSuperClass().Super(this, "draw");
}

PortfolioAlertsForm.prototype.submitForm = function (e, element)
{
    Events.cancel(e);

    var formContents = new Object(),
        currentForm;

    for( var i = 0; i < this.formComponents.length; i++ )
    {
        currentForm = this.formComponents[i].serialize();
        formContents[ currentForm.name ] = currentForm;
    }

    formContents = this.serializer.serialize(formContents);

    this.buffer.load({
        url: this.ALERT_API,
        method: 'post',
        data: {
            method: 'configureAlerts',
            alertsConfig: formContents 
        },
        onload: this.confirmSubmit,
        context: this,
        preventEval: true
    });
}

//----------------------------------------------------------------------------------------------------
//  AlertFormComponent is the base object from which each Alert Form extends.
//----------------------------------------------------------------------------------------------------
function AlertFormComponent (oArgs) 
{
    for( var field in oArgs )
    {
        this[field] = oArgs[field];
    }

    //  Add self reference to controlling "manager" object,
    //  in this case the AlertsHub object
    if (this.manager) 
    {
        this.manager.formComponents.push(this);
    }
}

AlertFormComponent.prototype.draw = function (name) 
{
    this.container = WSDOM.Element.create('fieldset', {}, null, this.manager.form);
    this.addToggle(name);

    var controlsDiv = WSDOM.Element.create('div', { className: 'controlsDiv' }, null, this.container );
    controlsDiv.style.display = 'block';
    /* Removed these due to display issues in IE 6
    controlsDiv.style.overflow = 'none';
    setTimeout(function(){controlsDiv.style.display = 'block'}, 10);
		*/
    return controlsDiv;
}

AlertFormComponent.prototype.serialize = function () 
{
    var company = this.manager.companyInfo;
    var o = {
        toggle:             this.toggle.checked,
        item:               this.item,
        name:               this.name,
        symbol:             company.BridgeSymbol,
        DisplaySymbol:      company.DisplaySymbol,// + ':' + company.ExchangeCode,
        PriceWhenSet:       company.Quote.LastPriceRaw,
        CurrencyISOCode:    company.Quote.CurrencyISOCode
    };

    if( this.AlertItem )
    {
        o.ItemID = this.AlertItem.ItemID;
    }

    return o;
}

AlertFormComponent.prototype.validate = function (o)
{
    return o;
}

AlertFormComponent.prototype.setAlertItem = function (oMyAlert)
{
    this.AlertItem = oMyAlert;
}

AlertFormComponent.prototype.hideCheckBox = function (bHide)
{
    if( bHide != undefined )
    {
        this._hideCheckBox = bHide;
    }
    return this._hideCheckBox;
}

AlertFormComponent.prototype.addToggle = function (name)
{
    var args = {
        id: name,
        name: name,
        type: 'checkbox'
    };

    if( this.hideCheckBox() )
    {
        args.checked = 'checked';
        args.className = 'hiddenCheckbox';
    }

    this.toggleDiv = WSDOM.Element.create('div', { className: 'toggleDiv' }, null, this.container);
    this.toggle = WSDOM.Element.create('input', args, null, this.toggleDiv);

    if( this.hideCheckBox() )
    {
        this.toggle.checked = true;
    }
}

AlertFormComponent.prototype.addDayPeriodOptions = function (select)
{
    var periods = [ 3, 5, 10, 30, 90 ],
        p;

    for( var i = 0; i < periods.length; i++ )
    {
        p = periods[i];

        WSDOM.Element.create('option', { value: p }, p + ' Day', select); 
    }
}

AlertFormComponent.prototype.addPercentOptions = function (select)
{
    var periods = [ 0.025, 0.05, 0.1, 0.2, 0.5, 1, 5 ],
        p;

    for( var i = 0; i < periods.length; i++ )
    {
        p = periods[i];

        WSDOM.Element.create('option', { value: p }, p*100 + '%', select);
    }
}

AlertFormComponent.prototype.addIndexOptions = function (select)
{
    var indices = ['SP500', 'DJI', 'NASDAQ', 'TSEA'],
        ind;
    
    var theIndices =  this.manager.companyInfo.Indices

		for(n in theIndices)
		{
			var curIndex = theIndices[n];
			WSDOM.Element.create('option', { value: curIndex.indId }, curIndex.indName, select);
		}

}

AlertFormComponent.prototype.populateCompanyInfo = function () { }

AlertFormComponent.prototype.displayError = function (error)
{
    if( this.error ){ WSDOM.Element.remove(this.error) };
    this.error = WSDOM.Element.create('div', { className: 'popupError' }, '! ' + error.message );
    WSDOM.Element.insertBefore( this.error, this.toggleDiv );
}

AlertFormComponent.prototype.setToggle = function ()
{
    WSDOM.Element.remove( WSDOM.Element.parseSelector('div.popupError'), this.container);
    this.toggle.checked = true;
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
function PriceDropsBelowAlert (oArgs)
{
    PriceDropsBelowAlert.Super(this, null, [oArgs]);
}
PriceDropsBelowAlert.Extend(AlertFormComponent);

PriceDropsBelowAlert.prototype.item = 1;
PriceDropsBelowAlert.prototype.name = 'priceDropsBelow';

PriceDropsBelowAlert.prototype.draw = function ()
{
    var container = PriceDropsBelowAlert.Super(this, 'draw', ['priceDropsBelowAlert']);

    WSDOM.Element.create('label', { 'for': 'priceDropsBelow' }, 'Price drops below', container);
    this.priceField = WSDOM.Element.create('input', { id: 'priceDropsBelow', name: 'priceDropsBelow', type: 'text', size: 6 }, null, container);

    this.quoteDisplay = WSDOM.Element.create('p', { id: 'equityAlertPriceField', className: 'secondaryInfo' }, 'Last price ', container);

    //  
    if( this.AlertItem )
    {
        this.priceField.value = this.AlertItem.price;
    }

    Events.add({
        element: this.priceField,
        type: 'keypress',
        handler: this.setToggle,
        context: this
    });
}

PriceDropsBelowAlert.prototype.populateCompanyInfo = function ()
{
    var quote            = this.manager.companyInfo.Quote;
    var changeFieldClass = ( quote.Change >= 0 ) ? 'positivePriceChange' : 'negativePriceChange';

    WSDOM.Element.create('span', {}, quote.LastPrice, this.quoteDisplay);
    WSDOM.Element.create('span', { className: changeFieldClass }, ' ' + quote.Change + ' ' + quote.ChangePercent, this.quoteDisplay);

    PriceDropsBelowAlert.Super(this, 'populateCompanyInfo');
}

PriceDropsBelowAlert.prototype.serialize = function ()
{
    var o = PriceDropsBelowAlert.Super(this, 'serialize');
    o.price = Number( this.priceField.value.replace(/[^\d\.]+/, '') );

    try {
        this.validate(o);
    } catch (e) {
        this.displayError(e);
        return false;
    }

    return o
}

PriceDropsBelowAlert.prototype.validate = function (params)
{
    PriceDropsBelowAlert.Super(this, 'validate', [params]);

    if( params.PriceWhenSet <= params.price )
    {
        throw new Error('Alert price is greater than current price.');
    }
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
function PriceRisesAboveAlert (oArgs)
{
    PriceRisesAboveAlert.Super(this, null, [oArgs]);
}
PriceRisesAboveAlert.Extend(AlertFormComponent);

PriceRisesAboveAlert.prototype.item = 2;
PriceRisesAboveAlert.prototype.name = 'priceRisesAbove';

PriceRisesAboveAlert.prototype.draw = function ()
{
    var container = PriceRisesAboveAlert.Super(this, 'draw', ['priceRisesAboveAlert']);

    WSDOM.Element.create('label', { 'for': 'priceRisesAbove' }, 'Price rises above', container);
    this.priceField = WSDOM.Element.create('input', { id: 'priceRisesAbove', name: 'priceRisesAbove', type: 'text', size: 6 }, null, container);

    this.quoteDisplay = WSDOM.Element.create('p', { id: 'equityAlertPriceField', className: 'secondaryInfo' }, 'Last price ', container);

    if( this.AlertItem )
    {
        this.priceField.value = this.AlertItem.price;
    }

    Events.add({
        element: this.priceField,
        type: 'keypress',
        handler: this.setToggle,
        context: this
    });
}

PriceRisesAboveAlert.prototype.populateCompanyInfo = function ()
{
    var quote            = this.manager.companyInfo.Quote;
    var changeFieldClass = ( quote.Change >= 0 ) ? 'positivePriceChange' : 'negativePriceChange';

    WSDOM.Element.create('span', {}, quote.LastPrice, this.quoteDisplay);
    WSDOM.Element.create('span', { className: changeFieldClass }, ' ' + quote.Change + ' ' + quote.ChangePercent, this.quoteDisplay);
}

PriceRisesAboveAlert.prototype.serialize = function ()
{
    var o = PriceRisesAboveAlert.Super(this, 'serialize');
    o.price = Number( this.priceField.value.replace(/[^\d\.]+/, '') );

    try {
        this.validate(o);
    } catch (e) {
        this.displayError(e);
        return false;
    }

    return o;
}

PriceRisesAboveAlert.prototype.validate = function (params)
{
    PriceRisesAboveAlert.Super(this, 'validate', [params]);

    if( params.PriceWhenSet >= params.price )
    {
        throw new Error('Alert price is less than current price.');
    }
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
function PeriodHighLowAlert (oArgs)
{
    PeriodHighLowAlert.Super(this, null, [oArgs]);
}
PeriodHighLowAlert.Extend(AlertFormComponent);

PeriodHighLowAlert.prototype.draw = function ()
{
    var container = PeriodHighLowAlert.Super(this, 'draw', ['periodHighLowAlert']);

    //  Create Dropdown
    WSDOM.Element.create('label', { 'for': 'alertPeriod' }, 'Makes a new 52 week', container);
    this.alertTypeSelect = select = WSDOM.Element.create('select', { id: 'alertPeriod', name: 'alertPeriod' }, null, container);
         WSDOM.Element.create('option', { value: 'periodHigh' }, 'High', select);
         WSDOM.Element.create('option', { value: 'periodLow' }, 'Low', select);

    if( this.AlertItem )
    {
        this.alertTypeSelect.value = this.AlertItem.name;
    }

    //  Message when dropdown is set to High
    var secondaryInfoHigh   = WSDOM.Element.create('p', { className: 'secondaryInfo' }, this.manager.companyInfo.DisplaySymbol.toUpperCase() + ' is ', container);
    this.highAmount          = WSDOM.Element.create('span', {}, null, secondaryInfoHigh);
        secondaryInfoHigh.appendChild( document.createTextNode(' off its 52 week high set ') );
    this.highDate            = WSDOM.Element.create('span', {}, null, secondaryInfoHigh);
        secondaryInfoHigh.style.display = 'block';

    //  Message when dropdown is set to Low 
    var secondaryInfoLow    = WSDOM.Element.create('p', { className: 'secondaryInfo' }, this.manager.companyInfo.DisplaySymbol.toUpperCase() + ' is ', container);
    this.lowAmount           = WSDOM.Element.create('span', {}, null, secondaryInfoLow);
        secondaryInfoLow.appendChild( document.createTextNode(' off its 52 week low set ') );
    this.lowDate             = WSDOM.Element.create('span', {}, null, secondaryInfoLow);
        secondaryInfoLow.style.display = 'none';

    function messageSwitch (e, element)
    {
        if( element.value == 'periodHigh' )
        {
            secondaryInfoHigh.style.display = 'block';
            secondaryInfoLow.style.display = 'none';
        }
        else
        {
            secondaryInfoLow.style.display = 'block';
            secondaryInfoHigh.style.display = 'none';
        }
    }

    Events.add({
        element: select,
        type: 'change',
        handler: messageSwitch,
        context: this
    });
}

PeriodHighLowAlert.prototype.populateCompanyInfo = function ()
{
    var quote = this.manager.companyInfo.Quote;

    this.highAmount.innerHTML = quote.HighOffset;
    this.highDate.innerHTML = quote.High52WeekDate;

    this.lowAmount.innerHTML = quote.LowOffset;
    this.lowDate.innerHTML = quote.Low52WeekDate;
}

PeriodHighLowAlert.prototype.serialize = function ()
{
    var o = PeriodHighLowAlert.Super(this, 'serialize');
    o.name = this.alertTypeSelect.value;
    o.item = ( o.name == 'periodHigh' ) ? 3 : 4;

    return o;
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
function PriceChangeAlert (oArgs)
{
    PriceChangeAlert.Super(this, null, [oArgs]);
}
PriceChangeAlert.Extend(AlertFormComponent);

PriceChangeAlert.prototype.item = 6;
PriceChangeAlert.prototype.name = 'priceChange';

PriceChangeAlert.prototype.draw = function ()
{
    var container = PriceChangeAlert.Super(this, 'draw', ['priceChangeAlert']);

    WSDOM.Element.create('label', { 'for': 'priceChange' }, 'Price changes', container);
    this.priceChangeSelect = WSDOM.Element.create('select', { id: 'priceChange', name: 'priceChange' }, null, container);
        this.addPercentOptions(this.priceChangeSelect);

    WSDOM.Element.create('label', { 'for': 'priceChange' }, 'from prior close', container);

    var secondaryInfo = WSDOM.Element.create('p', { id: 'priceChangeAlertField', className: 'secondaryInfo' }, null, container);
    this.prevClose = WSDOM.Element.create('span', { id: 'prevClose' }, null, secondaryInfo);
        secondaryInfo.appendChild( document.createTextNode( ' on ' ) );
    this.prevCloseDate = WSDOM.Element.create('span', { id: 'prevCloseDate' }, null, secondaryInfo);
}

PriceChangeAlert.prototype.populateCompanyInfo = function ()
{
    var quote = this.manager.companyInfo.Quote;

    this.prevClose.innerHTML = quote.PreviousClose;
    this.prevCloseDate.innerHTML = quote.PreviousCloseDate;
}

PriceChangeAlert.prototype.serialize = function ()
{
    var o = PriceChangeAlert.Super(this, 'serialize');
    o.PricePercentChange = this.priceChangeSelect.value;

    return o;
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
function PriceAverageAlert (oArgs)
{
    PriceAverageAlert.Super(this, null, [oArgs]);
}
PriceAverageAlert.Extend(AlertFormComponent);

PriceAverageAlert.prototype.item = 395;
PriceAverageAlert.prototype.name = 'priceAverage';

PriceAverageAlert.prototype.draw = function ()
{
    var container = PriceAverageAlert.Super(this, 'draw', ['priceAverageAlert']);

    WSDOM.Element.create('label', { 'for': 'priceAveragePeriod' }, 'Price crosses its', container);
    this.periodSelect = WSDOM.Element.create('select', { id: 'priceAveragePeriod', name: 'priceAveragePeriod' }, null, container);
                 this.addDayPeriodOptions(this.periodSelect);

    WSDOM.Element.create('label', { 'for': 'priceAveragePercent' }, 'moving average by', container);
    this.percentSelect = WSDOM.Element.create('select', { id: 'priceAveragePercent', name: 'priceAveragePercent' }, null, container);
                 this.addPercentOptions(this.percentSelect);
}

PriceAverageAlert.prototype.serialize = function ()
{
    var o = PriceAverageAlert.Super(this, 'serialize');
    o.MovingAverageDays = this.periodSelect.value
    o.Percent = this.percentSelect.value;
    o.Direction = 'either';

    return o;
}

PriceAverageAlert.prototype.addDayPeriodOptions = function (select)
{
    var periods = [ 15, 30, 50, 60, 90, 200 ],
        p;

    for( var i = 0; i < periods.length; i++ )
    {
        p = periods[i];

        WSDOM.Element.create('option', { value: p }, p + ' Day', select); 
    }
}

//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
function VolumeAverageAlert (oArgs)
{
    VolumeAverageAlert.Super(this, null, [oArgs]);
}
VolumeAverageAlert.Extend(AlertFormComponent);

VolumeAverageAlert.prototype.item = 430;
VolumeAverageAlert.prototype.name = 'volumeAverage';

VolumeAverageAlert.prototype.draw = function ()
{
    var container = VolumeAverageAlert.Super(this, 'draw', ['volumeAverageAlert']);
    
    WSDOM.Element.create('label', { 'for': 'tradingVolumePeriod' }, 'Trading volume exceeds', container);
    this.periodSelect = WSDOM.Element.create('select', { id: 'tradingVolumePeriod', name: 'tradingVolumePeriod' }, null, container);
                 this.addDayPeriodOptions(this.periodSelect);

    WSDOM.Element.create('label', { 'for': 'tradingVolumePercent' }, 'average by', container);
    this.percentSelect = WSDOM.Element.create('select', { id: 'tradingVolumePercent', name: 'tradingVolumePercent' }, null, container);
                 this.addPercentOptions(this.percentSelect);
}

VolumeAverageAlert.prototype.serialize = function ()
{
    var o = VolumeAverageAlert.Super(this, 'serialize');
    o.MVAInterval = this.periodSelect.value;
    o.Percent = this.percentSelect.value;

    return o;
}

VolumeAverageAlert.prototype.addDayPeriodOptions = function (select)
{
    var periods = [ 10, 50 ],
        p;

    for( var i = 0; i < periods.length; i++ )
    {
        p = periods[i];

        WSDOM.Element.create('option', { value: p }, p + ' Day', select); 
    }
}


//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------
function PriceVSIndexAlert (oArgs)
{
    PriceVSIndexAlert.Super(this, null, [oArgs]);
}
PriceVSIndexAlert.Extend(AlertFormComponent);

PriceVSIndexAlert.prototype.item = 436;
PriceVSIndexAlert.prototype.name = 'priceVSIndex';

PriceVSIndexAlert.prototype.draw = function ()
{
    var container = PriceVSIndexAlert.Super(this, 'draw', ['priceVSIndexAlert']);

    WSDOM.Element.create('label', { 'for': 'priceVSIndexPercent' }, 'Price rises or falls', container);
    this.percentSelect = WSDOM.Element.create('select', { id: 'priceVSIndexPercent', name: 'priceVSIndexPercent' }, null, container);
        this.addPercentOptions(this.percentSelect);

    WSDOM.Element.create('label', { 'for': 'priceVSIndexIndex' }, 'faster than the', container);
    this.indexSelect = WSDOM.Element.create('select', { id: 'priceVSIndexIndex', name: 'priceVSIndexIndex' }, null, container);
        this.addIndexOptions(this.indexSelect);

    WSDOM.Element.create('label', { 'for': 'priceVSIndexPeriod' }, 'over', container);
    this.periodSelect = WSDOM.Element.create('select', { id: 'priceVSIndexPeriod', name: 'priceVSIndexPeriod' }, null, container);
        this.addDayPeriodOptions(this.periodSelect);
}

PriceVSIndexAlert.prototype.serialize = function ()
{
    var o = PriceVSIndexAlert.Super(this, 'serialize');

    o.Days = this.periodSelect.value;
    o.PercentChange = this.percentSelect.value;
    o.Index = this.indexSelect.value;

    return o;
}

PriceVSIndexAlert.prototype.addDayPeriodOptions = function (select)
{
    var periods = [ 1, 5, 10 ],
        p;

    for( var i = 0; i < periods.length; i++ )
    {
        p = periods[i];

        WSDOM.Element.create('option', { value: p }, p + ' Day', select); 
    }
}
//----------------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------------

function PortfolioAlert (oArgs)
{
    PortfolioAlert.Super(this, null, [oArgs]);
}
PortfolioAlert.Extend(AlertFormComponent);

PortfolioAlert.prototype.item = 450;
PortfolioAlert.prototype.name = 'portfolioDaily';
PortfolioAlert.prototype.weeklyMessage = 'Weekly alerts are sent at 7pm ' + WSODTIMEZONE + ' on Friday.';
PortfolioAlert.prototype.monthlyMessage = 'Monthly alerts are sent at 7pm ' + WSODTIMEZONE + ' <br />on the last day of the month.';

PortfolioAlert.prototype.draw = function ()
{
    this.drawPeriodControls();
    this.drawTimeControls();
    this.drawPeriodMessages();

    Events.add({
        element: this.periodSelect,
        type: 'change',
        handler: this.toggleTimeSelect,
        context: this
    });
}

PortfolioAlert.prototype.drawPeriodControls = function ()
{
    this.periodContainer = WSDOM.Element.create('fieldset', {}, null, this.manager.form);

    WSDOM.Element.create('label', { 'for': 'alertPeriod' }, 'Send portfolio summary', this.periodContainer);
    this.periodSelect = WSDOM.Element.create('select', { id: 'alertPeriod', name: 'alertPeriod' }, null, this.periodContainer);
        this.addPeriodOptions(this.periodSelect);

    var summary = this.manager.summary;

    if( !this.manager.hub )
    {
        this.performanceDisplay = WSDOM.Element.create('p', { id: 'performanceDisplay', className: 'secondaryInfo' }, 'Last total ', this.periodContainer);
        WSDOM.Element.create('span', {}, 
                summary.currentValueWithCurrency + ' ' + 
                summary.currentGainOrLossDecimalWithCurrency + ' ' +
                summary.currentGainOrLossPercent, this.performanceDisplay);
    }
    else
    {
        this.performanceDisplay = WSDOM.Element.create('p', { id: 'performanceDisplay', className: 'secondaryInfo' }, '&nbsp;', this.periodContainer);
    }
}

PortfolioAlert.prototype.drawTimeControls = function ()
{
    this.timeContainer = WSDOM.Element.create('fieldset', {}, null, this.manager.form);

    WSDOM.Element.create('label', { 'for': 'alertTime' }, 'Send alerts at', this.timeContainer);
    this.timeSelect = WSDOM.Element.create('select', { id: 'alertTime', name: 'alertTime' }, null, this.timeContainer);
        this.addTimeOptions(this.timeSelect);

    WSDOM.Element.create('p', { className: 'secondaryInfo' }, 'All times ' + WSODTIMEZONE, this.timeContainer);
}

PortfolioAlert.prototype.toggleTimeSelect = function (e, element)
{
    this.timeContainer.style.display = ( element.value == 32) ? 'block' : 'none';

    if( element.value == 32 )
    {
        WSDOM.Element.removeClass(this.timeContainer, 'wsodHidden');
        WSDOM.Element.addClass(this.weeklyContainer, 'wsodHidden');
        WSDOM.Element.addClass(this.monthlyContainer, 'wsodHidden');
        this.item = 450;
        this.name = 'portfolioDaily';
    }
    else if( element.value == 16 )
    {
        WSDOM.Element.addClass(this.timeContainer, 'wsodHidden');
        WSDOM.Element.removeClass(this.weeklyContainer, 'wsodHidden');
        WSDOM.Element.addClass(this.monthlyContainer, 'wsodHidden');
        this.item = 451;
        this.name = 'portfolioPeriod';
    }
    else if( element.value == 8 )
    {
        WSDOM.Element.addClass(this.timeContainer, 'wsodHidden');
        WSDOM.Element.addClass(this.weeklyContainer, 'wsodHidden');
        WSDOM.Element.removeClass(this.monthlyContainer, 'wsodHidden');
        this.item = 451;
        this.name = 'portfolioPeriod';
    }
}

PortfolioAlert.prototype.drawPeriodMessages = function ()
{
    this.weeklyContainer = WSDOM.Element.create('fieldset', { className: 'wsodHidden' }, null, this.manager.form);
        WSDOM.Element.create('p', {}, this.weeklyMessage, this.weeklyContainer);
    this.monthlyContainer = WSDOM.Element.create('fieldset', { className: 'wsodHidden' }, null, this.manager.form);
        WSDOM.Element.create('p', {}, this.monthlyMessage, this.monthlyContainer);
}

PortfolioAlert.prototype.serialize = function ()
{
    var o = {
        toggle: true,
        item: this.item,
        name: this.name,
        ContainerID: this.manager.summary.ContainerID
    };

	if (this.name == "portfolioPeriod") 
	{
	    o.Period = this.periodSelect.value;
	}
	else if (this.name == "portfolioDaily") 
	{
	    o.Timeframe = this.timeSelect.value;
	}
		
		
    if( this.AlertItem )
    {
        o.ItemID = this.AlertItem.ItemID;
    }

    return o;
}

PortfolioAlert.prototype.addPeriodOptions = function (select)
{
    var periods = {
        'Daily':        32,
        'Weekly':       16,
        'Monthly':      8
    }, p;

    for( var name in periods )
    {
        p = periods[name];

        WSDOM.Element.create('option', { value: p }, name, select);
    }
}

/*
PortfolioAlert.prototype.TIMEPERIODS = {
    'midnight': 16,
    '1:00 am': 17,
    '2:00 am': 18,
    '3:00 am': 19,
    '4:00 am': 20,
    '5:00 am': 21,
    '6:00 am': 22,
    '7:00 am': 23,
    '8:00 am': 0,
    '9:00 am': 1,
    '10:00 am': 2,
    '11:00 am': 3,
    'noon': 4,
    '1:00 pm': 5,
    '2:00 pm': 6,
    '3:00 pm': 7,
    '4:00 pm': 8,
    '5:00 pm': 9,
    '6:00 pm': 10,
    '7:00 pm': 11,
    '8:00 pm': 12,
    '9:00 pm': 13,
    '10:00 pm': 14,
    '11:00 pm': 15
};

PortfolioAlert.prototype.TIMEPERIODS = {
    'midnight': 5,
    '1:00 am': 6,
    '2:00 am': 7,
    '3:00 am': 8,
    '4:00 am': 9,
    '5:00 am': 10,
    '6:00 am': 11,
    '7:00 am': 12,
    '8:00 am': 13
    '9:00 am': 14,
    '10:00 am': 15,
    '11:00 am': 16,
    'noon': 17,
    '1:00 pm': 5,
    '2:00 pm': 6,
    '3:00 pm': 7,
    '4:00 pm': 8,
    '5:00 pm': 9,
    '6:00 pm': 10,
    '7:00 pm': 11,
    '8:00 pm': 12,
    '9:00 pm': 13,
    '10:00 pm': 14,
    '11:00 pm': 15
};
*/

PortfolioAlert.prototype.getTimePeriods = function ()
{
    var times = new Array();

    for( var meridian in {'am': 0, 'pm': 1} )
    {
        for( var hour = 0; hour < 12; hour++ )
        {
            if(hour == 0)
            { 
                times.push( meridian == 'am' ? 'midnight' : 'noon' );
                continue;
            }

            times.push( hour + ':00 ' + meridian );
        }
    }

    return times;
}


PortfolioAlert.prototype.addTimeOptions = function (select)
{
    var times = this.getTimePeriods(),
        t, o, v, h;

    for( var i = 0; i < times.length; i++ )
    {
        //v = (i + offset >= 24) ? ((i + offset) - 24) : (i + offset);
        h = i;
        v = (h < 0) ? (24 + h) : h;
        o = WSDOM.Element.create('option', { value: Math.pow(2, v) }, times[i], select);
        if( times[i] == 'noon' ){ o.selected = true };
    }
}


//----------------------------------------------------------------------------------------------------
//  Error Popup Window (alert replacement)
//----------------------------------------------------------------------------------------------------

function ErrorPopup ()
{
    ErrorPopup.Super(this);
    this.hasCloseLink(false);
}
ErrorPopup.Extend(Popup);

ErrorPopup.prototype.draw = function (title, message)
{
    this.setTitleText(title);

    var textDiv = WSDOM.Element.create('div', { className: 'messageDiv' }, null, this.getContent());
    WSDOM.Element.create('p', {}, message, textDiv);

    this.drawConfirmButton();
    
    ErrorPopup.Super(this, 'draw');
}

ErrorPopup.prototype.drawConfirmButton = function ()
{
    var buttonDiv = WSDOM.Element.create('div', { className: 'buttonDiv' }, null, this.getContent());
    var outerButton = WSDOM.Element.create('div', { className: 'basicButton' }, null, buttonDiv);
    var button = WSDOM.Element.create('div', {}, 'Ok', outerButton);

    Events.add({
        element: button,
        type: 'click',
        handler: this.close,
        context: this
    });
}
